<template>
  <div>
    <div class="transfer">
      <div class="leftTransfer">
        <div class="leftTransfer_title">
          <span>{{ titles[0] }}</span>
          <span>{{ left.transferDataChecked.length }}/{{ left.childrenNum || 0 }}</span>
        </div>
        <el-input
            @input="transferInputLeft"
            class="transfer_input"
            size="small"
            placeholder="请输入一级结构内容"
            v-model="left.inputValue"
        />
        <div style="margin: 5px 0"></div>
        <el-scrollbar class="transfer_group">
          <el-tree
              :data="left.transferData"
              show-checkbox
              node-key="key"
              default-expand-all
              :empty-text="'暂无数据'"
              :expand-on-click-node="false"
              :props="defaultProps"
              @check="leftHandleChecked"
          />
        </el-scrollbar>
        <el-pagination
            small
            class="pagination"
            :pager-count="5"
            layout="prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
        />
      </div>
      <div class="transferButton">
        <el-button type="primary" :disabled="!left.transferDataChecked.length" @click="push">
          <el-icon>
            <ArrowRight/>
          </el-icon>
        </el-button>
        <el-button type="primary" :disabled="!right.transferDataChecked.length" @click="del">
          <el-icon>
            <ArrowLeft/>
          </el-icon>
        </el-button>
      </div>
      <div class="rightTransfer">
        <div class="rightTransfer_title">
          <span>{{ titles[1] }}</span>
          <span>{{ right.transferDataChecked.length }}/{{ right.transferData.length }}</span>
        </div>
        <el-input
            @input="transferInputRight"
            class="transfer_input"
            placeholder="请输入一级结构内容"
            size="small"
            v-model="right.inputValue"
        />
        <div style="margin: 5px 0"></div>
        <el-scrollbar class="transfer_group">
          <el-tree
              :data="right.transferData"
              show-checkbox
              node-key="key"
              :empty-text="'暂无数据'"
              default-expand-all
              :expand-on-click-node="false"
              :props="defaultPropsRight"
              @check="rightHandleChecked"
          />
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>

<script setup name="TreeTransfer">

const {proxy} = getCurrentInstance()

const emit = defineEmits()
const props = defineProps({
  titles: {
    type: Array,
    default: () => ['待选列表', '已选列表']
  },
  list: {
    type: Array,
    default: () => []
  },
  total: {
    type: Number,
    default: 0
  }
})

/** Data*/
const tree = reactive({
  queryParams: {
    page: 1,
    per_page: 10
  },
  left: {
    inputValue: '',
    isIndeterminate: false, //半选按钮
    checkAll: false, //是否点击全选
    transferData: [], //穿梭框左侧全部数据
    transferDataAll: [], //穿梭框左侧全部数据记录
    transferDataChecked: [], //穿梭框左侧选中数据
    originData: [] //原始数据
  },
  right: {
    inputValue: '',
    isIndeterminate: false, //半选按钮
    checkAll: false, //是否点击全选
    transferData: [], //穿梭框右侧全部数据
    transferDataAll: [], //穿梭框左侧全部数据记录
    transferDataChecked: [] //穿梭框右侧选中数据
  },
  defaultProps: {
    label: 'label',
    id: 'key',
    pid: 'key2',
    children: 'children'
  },
  defaultPropsRight: {
    label: 'label2',
    id: 'key',
    pid: 'key2',
    children: 'null'
  }
})
const {left, right, defaultProps, defaultPropsRight, queryParams} = toRefs(tree)

onMounted(() => {
  initTransferData()
})

/** Methods*/
//初始化，只支持二级树形结构
async function initTransferData() {
  let _ = proxy
  // const {data: res} = await _.$H.post(_.$A.install.getInstallPerson, queryParams.value)
  // props.list = (res.data || []).map((i) => {
  //   return {
  //     label: i.label,
  //     key: i.key,
  //     children: i.apiInstallPersonVOList
  //   }
  // })
  let childrenNum = 0 //子树数
  left.value.transferData = props.list.map((item) => {
    if (item.children) {
      item.children.forEach((item2) => {
        item2.label2 = item.label + '-' + item2.label
        item2.key2 = item.key
      })
      childrenNum += item.children.length
    }
    if (item.children.length === 0) {
      item.disabled = true
    }
    return item
  })
  left.value.childrenNum = childrenNum
  left.value.originData = JSON.parse(JSON.stringify(left.value.transferData))
  left.value.transferData.map((item, index) => {
    item.page = queryParams.value.page
  })
  left.value.transferDataAll = left.value.transferData
  // 删除左侧的数据
  delLeftData()
}


//移除左侧数据
function delLeftData() {
  // 获得一个右边的数据，只有纯id
  let checkedIdArr = right.value.transferData.map((item) => {
    return item[defaultProps.value.id]
  })
  // 左侧数据删除
  left.value.transferData = left.value.transferData.filter((item) => {
    // 删除时，判断左侧的一级数据的二级是否全部转移，如果是，则一级也删除，否则，只删除二级
    if (item.children && item.children.length > 0) {
      let childrenArr = item.children.map((item2) => {
        return item2[defaultProps.value.id]
      })
      if (childrenArr.every((item3) => checkedIdArr.includes(item3))) {
        return false
      } else {
        item.children = item.children.filter((item2) => {
          if (!checkedIdArr.includes(item2[defaultProps.value.id])) {
            return item2
          }
        })
        return item
      }
    } else {
      if (!checkedIdArr.includes(item[defaultProps.value.id])) {
        return item
      }
    }
  })
}

// 左侧勾选数据
function leftHandleChecked(data, nodes) {
  // console.log(data, nodes, 'data做选中')
  left.value.transferDataChecked = (nodes.checkedNodes || []).filter((item) => item.children == undefined)
}

// 右侧勾选数据
function rightHandleChecked(data, nodes) {
  // console.log(data, nodes, 'data做选中')
  right.value.transferDataChecked = nodes.checkedNodes || []
}

// 穿梭框选中数据
function push() {
  // 数据移到右侧
  // console.log('之前', right.transferData)
  right.value.transferData = [...right.value.transferData, ...left.value.transferDataChecked].sort(
      (a, b) => {
        // console.log('之', a['key2'], b)
        return Number.parseInt(a['key2'].slice(13)) - Number.parseInt(b['key2'].slice(13))
      }
  )
  // console.log('之后',right.transferData)
  right.value.transferDataAll = right.value.transferData
  // 删除左侧的数据
  delLeftData()
  left.value.transferDataAll = left.value.transferData
  // 每次推送完之后，重置选中框
  left.value.transferDataChecked = []
  left.value.isIndeterminate = false
  left.value.checkAll = false
  emit('selected', right.value.transferData);
}

// 穿梭框过滤数据 回显的时候根据current回显到当前
function del() {
  //过滤当前页选中的数据
  let arr = right.value.transferDataChecked || []
  left.value.originData.forEach((item) => {
    let node = arr.filter((item2) => item2.key2 === item.key)
    if (node.length) {
      let ev = left.value.transferData.find((item2) => {
        return node[0].key2 === item2.key
      })
      // console.log(ev, 'ev11')
      if (ev) {
        ev.children = [...ev.children, ...node]
      } else {
        let ev2 = left.value.originData.find((item2) => {
          return node[0].key2 === item2.key
        })
        if (ev2)
          left.value.transferData.push({
            ...ev2,
            children: [...node]
          })
      }
    }
  })
  left.value.transferDataAll = left.value.transferData
  // 获得一个右边的数据，只有纯id
  let checkedIdArr = right.value.transferDataChecked.map((item) => {
    return item[defaultProps.value.id]
  })
  // 删除选中的数据
  right.value.transferData = right.value.transferData.filter((item) => {
    if (!checkedIdArr.includes(item[defaultProps.value.id])) {
      return item
    }
  })
  right.value.transferDataAll = right.value.transferData
  // 每次推送完之后，重置选中框
  right.value.transferDataChecked = []
  right.value.isIndeterminate = false
  right.value.checkAll = false
}

// 分页
function handleCurrentChange(val) {
  queryParams.value.page = val
  initTransferData()
}

// 左侧浅层检索
function transferInputLeft() {
  console.log('search', left.value.transferData)
  if (left.value.inputValue) {
    left.value.transferData = left.value.transferData.filter(
        (p) => p[defaultProps.value.label].indexOf(left.value.inputValue) !== -1
    )
  } else {
    left.value.transferData = left.value.transferDataAll
  }
}

// 右侧浅层检索
function transferInputRight() {
  if (right.value.inputValue) {
    right.value.transferData = right.value.transferData.filter(
        (p) => p[defaultProps.value.label].indexOf(right.value.inputValue) !== -1
    )
  } else {
    right.value.transferData = right.value.transferDataAll
  }
}

</script>

<style lang="less" scoped>
.transfer {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .transferButton {
    .el-button {
      display: block;
      margin: 10px 0;
    }
  }

  .el-checkbox {
    line-height: 30px;
  }

  .transfer_input {
    margin: 10px 15px 0 15px;
    width: 85%;

    .el-input--medium .el-input__inner {
      height: 36px;
      line-height: 36px;
      border-radius: 16px;
    }
  }

  .leftTransfer,
  .rightTransfer {
    height: 350px;
    border: 1px solid #e6ebf5;
    border-radius: 4px;
    overflow: hidden;
    background: #ffffff;
    display: inline-block;
    vertical-align: middle;
    width: 250px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    position: relative;
    margin: 0 10px;

    .el-checkbox {
      display: block;
    }

    .pagination {
      position: absolute;
      bottom: -4px;
      right: 0;
    }

    .leftTransfer_title,
    .rightTransfer_title {
      display: flex;
      justify-content: space-between;
      height: 40px;
      line-height: 40px;
      background: #f5f7fa;
      margin: 0;
      padding-left: 15px;
      border-bottom: 1px solid #e6ebf5;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      color: #000000;
      padding-right: 15px;
      align-items: center;
    }
  }
}

.transfer_group {
  padding-left: 15px;
  height: calc(100% - 105px);
}
</style>

